package com.happypets.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.happypets.model.PageBean;
import com.happypets.model.PetBean;
import com.happypets.services.PetService;
import com.happypets.servicesImpl.PetServiceImpl;

public class DogsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	PetService petService = new PetServiceImpl();
	PageBean pageBean = new PageBean();
	int petKind = 1;//1:dog  2:cat  3:bird
	
    public DogsServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		System.out.println("------dogsServlet start");
		
		//最大页数
		int maxPageNumber = 1;
		//当前页
		int currentPageNumber = 1;
		//每页显示多少条
		int showNumber = 3;
		//一共多少
		int allNumber = 0;
		
		String temp = (String)request.getParameter("currentPageNumber");
		if(temp != null){
			currentPageNumber = Integer.parseInt(temp);
		}
		temp = (String)request.getParameter("showNumber");
		if(temp != null){
			showNumber = Integer.parseInt(temp);
			//currentPageNumber = 1;//返回到第一页
			
			System.out.println("showNumber"+temp);
			
		}
		if(request.getParameter("kind") != null){
			petKind = Integer.parseInt(request.getParameter("kind"));
		}
		
		String queryCount = "select a.id from animalsinfo a where a.bigcategoryid = "+petKind;
		
		allNumber = petService.query(queryCount).size();
		//计算最大页数
		maxPageNumber = allNumber%showNumber==0?allNumber/showNumber:allNumber/showNumber+1;
		
		pageBean.setAllNumber(allNumber);
		pageBean.setCurrentPageNumber(currentPageNumber);
		pageBean.setMaxPageNumber(maxPageNumber);
		pageBean.setShowNumber(showNumber);
																																					//此处可设置为通用
		List<PetBean> pets = (List<PetBean>) petService.pageQuery(petKind, showNumber, currentPageNumber);
		
		
		//修改pageQuery方法
		//设置成可关键字查询的方法
		
		
		//进行相关处理
		String path = request.getContextPath();
		
		//通过获取主页传递的dogs来得到数据，如果为空的话就重新获取，不为空则利用
		//但是会发生不同步bug，后台修改但是前台并不会显示
		HttpSession session = request.getSession();
		
		session.setAttribute("dogsFlag", "yes");
		session.setAttribute("pets", pets);
		session.setAttribute("pageBean", pageBean);
		
		/**
		 * 移除搜索用的东西
		 */
		session.removeAttribute("category");
		session.removeAttribute("color");
		session.removeAttribute("shape");
		session.removeAttribute("keywords");
		
		response.sendRedirect(path+"/web/dogs.jsp");
		
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
